package com.mju.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mju.utils.RespData;

import lombok.extern.slf4j.Slf4j;

@RestController
@Slf4j
public class KaptchaController {

	@Autowired
	private DefaultKaptcha defaultKaptcha;
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;	
	@Value("${custom.kaptchaExpired}")
	private int exp;
	@Value("${custom.kaptchaRedisKey}")
	private String kaptchaRedisKey;
	
	@GetMapping("/kaptcha")
	public RespData kaptcha() throws IOException {
		
		String code= defaultKaptcha.createText();//生成验证码
		log.info(code);
		String uuid=UUID.randomUUID().toString();
		redisTemplate.opsForValue().set(kaptchaRedisKey+uuid,
				code, Duration.ofMinutes(exp));
		
		BufferedImage image = defaultKaptcha.createImage(code);//生成图片
		
		//图片放在输出流中
		ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", outputStream);
		
		//利用输出流把图片转换为base64格式
		Base64.Encoder encoder=  Base64.getEncoder();
		byte[] imgByte=encoder.encode(outputStream.toByteArray());
		String base64Image=new String(imgByte);
		
		Map<String,Object> map=new HashMap<>();//为了返回给前端
		map.put("uuid", uuid);
		map.put("kaptchaImg", "data:image/jpeg;base64,"+base64Image);
		
		return RespData.data(map);
	}
}
